<?php

if ($has_db_settings) {
    include $settings_path;
    mysql_connect($host, $login, $password);
    mysql_select_db($db_name);
    mysql_query("SET NAMES 'utf8';");
    mysql_query("SET CHARACTER SET 'utf8';");
    mysql_query("SET SESSION collation_connection = 'utf8_general_ci';");
}

function addslsh($val) {
    if (is_array($val)) {
        foreach ($val as $key => $value) {
            $val[$key] = addslsh($value);
        }
    } else {
        $val = addslashes($val);
    }
    return $val;
}

function mysql_insert($table, $insert) {
    $sql = "INSERT INTO `" . $table . "` (`" . implode("`, `", array_keys($insert)) . "`) VALUES ('" . implode("', '", array_values(addslsh($insert))) . "')";
    mysql_query($sql);
    return mysql_insert_id();
}

function mysql_insert_if_absent($table, $insert, $check) {
    $sql = "SELECT `id` FROM `" . $table . "` WHERE 1=1 ";
    foreach ($check as $key => $value) {
        $sql .= " AND `" . $key . "` = '" . addslashes($value) . "' ";
    }
    $id = @mysql_result(mysql_query($sql), 0);
    $id = $id ? $id : mysql_insert($table, $insert);
    return $id;
}

function mysql_select_array($q) {
    $result = array();
    $query = mysql_query($q);
    if ($query) {
        while ($row = mysql_fetch_assoc($query)) {
            $result[] = $row;
        }
    }
    return $result;
}

function mysql_value($q) {
    $sql = $q;
    $result = array();
    if ($query = mysql_query($sql)) {
        while ($row = mysql_fetch_row($query)) {
            array_push($result, array_shift($row));
        }
    }
    $result = count($result) == 0 ? null : $result[0];
    return $result;
}

function mysql_row_assoc($sql) {
    $query = mysql_query($sql);
    $row = mysql_fetch_assoc($query);
    return $row;
}

function mysql_insert_or_update($table, $insert, $check, $update = "") {
    $sql = "SELECT `id` FROM `" . $table . "` WHERE 1=1 ";
    foreach ($check as $key => $value) {
        $sql .= " AND `" . $key . "` = '" . $value . "' ";
    }
    if ($id = mysql_value($sql)) {
        mysql_update($table, $update ? $update : $insert, $id);
    } else {
        $id = mysql_insert($table, $insert);
    }
    return $id;
}

function mysql_update($table, $update, $where, $selector_type = "AND") {
    $sql = "UPDATE `" . $table . "` SET ";
    foreach ($update as $key => $value) {
        $sql .= "`" . $key . "` = '" . $value . "', ";
    }
    $sql = preg_replace("#,$#si", '', trim($sql));
    if (is_array($where)) {
        $sql .= " WHERE 1=1 ";
        foreach ($where as $key => $value) {
            $sql .= " " . $selector_type . " `" . $key . "` = '" . $value . "'";
        }
    } else {
        $sql .= " WHERE `id` = '" . $where . "'";
    }
    mysql_query($sql);
}